package com.ferry.transport.api;

import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by daiyong
 * 连接管理器
 */
public class ConnectionManager {

	private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class);

	private final ConcurrentMap<UnResolvedAddress, CopyOnWriteArrayList<Connection>> connections = Maps.newConcurrentMap();

	public void manage(Connection connection) {
		UnResolvedAddress address = connection.getAddress();
		CopyOnWriteArrayList<Connection> list = connections.get(address);
		if (list == null) {
			CopyOnWriteArrayList<Connection> newList = new CopyOnWriteArrayList<>();
			list = connections.putIfAbsent(address, newList);
				if (list == null) {
					list = newList;
			}
		}
		list.add(connection);
	}

	/**
	 * 取消对指定地址的自动重连
	 */
	public void cancelAutoReconnect(UnResolvedAddress address) {
		CopyOnWriteArrayList<Connection> list = connections.remove(address);
		if (list != null) {
			for (Connection c : list) {
				c.setReconnect(false);
			}
			logger.warn("Cancel reconnect to: {}.", address);
		}
	}

	/**
	 * 取消对所有地址的自动重连
	 */
	public void cancelAllAutoReconnect() {
		for (UnResolvedAddress address : connections.keySet()) {
			cancelAutoReconnect(address);
		}
	}

}
